/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
public:
    void _treeTo(Node* root, Node*& prev)
    {
        if (root == nullptr)
            return;
        _treeTo(root->left, prev);
        root->left = prev;
        if (prev)
            prev->right = root;
        prev = root;
        _treeTo(root->right, prev);
    }
    Node* treeToDoublyList(Node* root) {
        if (root == nullptr)
            return root;
        Node* prev = nullptr;
        _treeTo(root, prev);
        Node* first = root;
        Node* second = root;
        while (first->left)
            first = first->left;
        while (second->right)
            second = second->right;
        first->left = second;
        second->right = first;
        return first;
    }
};